package com.atguigu.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.order.entity.TOrder;
import com.atguigu.order.entity.TPayLog;
import com.atguigu.order.mapper.TPayLogMapper;
import com.atguigu.order.service.TOrderService;
import com.atguigu.order.service.TPayLogService;
import com.atguigu.order.util.HttpClient;
import com.atguigu.servicebase.exceptionhandler.GuiliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPayUtil;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-08-18
 */
@Service
public class TPayLogServiceImpl extends ServiceImpl<TPayLogMapper, TPayLog> implements TPayLogService {

    @Autowired
    TOrderService tOrderService;

    //实现生成二维码
    @Override
    public Map createWxZfEwm(String order_no) {
        try {
            //根据订单号查询订单数据
            QueryWrapper<TOrder> wrapper = new QueryWrapper();
            wrapper.eq("order_no",order_no);
            TOrder tOrder = tOrderService.getOne(wrapper);
            //使用map设置生成二维码需要的参数
            Map m = new HashMap();
            m.put("appid","wx74862e0dfcf69954");
            m.put("mch_id", "1558950191");
            m.put("nonce_str", WXPayUtil.generateNonceStr());
            m.put("body", tOrder.getCourseTitle()); //课程标题
            m.put("out_trade_no", order_no); //订单号
            m.put("total_fee", tOrder.getTotalFee().multiply(new BigDecimal("100")).longValue()+"");
            m.put("spbill_create_ip", "127.0.0.1");
            m.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n");
            m.put("trade_type", "NATIVE");
            //发送httpclient请求，传送参数xml格式      微信支付宝提供的固定地址
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //通过sexml进行加密
            client.setXmlParam(WXPayUtil.generateSignedXml(m,"T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            //执行发送post请求
            client.post();
            //得到发送请求返回的数据,其为xml模式
            String contentXml = client.getContent();
            //把xml格式转换为map格式
            Map<String,String> resultMap = WXPayUtil.xmlToMap(contentXml);
            //最终返回数据的map
            Map map = new HashMap();
            map.put("out_trade_no", order_no);
            map.put("course_id", tOrder.getCourseId());
            map.put("total_fee", tOrder.getTotalFee());
            map.put("result_code", resultMap.get("result_code"));  //返回二维码操作状态码
            map.put("code_url", resultMap.get("code_url"));     //二维码地址
            return map;
        }catch (Exception e){
            throw new GuiliException(20001,"生成二维码失败");
        }
    }

    //查询订单的支付状态
    @Override
    public Map<String, String> queryPayStatus(String order_no) {
        try{
            Map m = new HashMap<>();
            m.put("appid", "wx74862e0dfcf69954");
            m.put("mch_id", "1558950191");
            m.put("out_trade_no", order_no);
            m.put("nonce_str", WXPayUtil.generateNonceStr());

            //发送固定地址的请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(m,"T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();
            //得到返回的内容
            //由于传回的内同为xml格式，需重新将其转换为map
            String xml = client.getContent();
            Map<String,String> resultMap =WXPayUtil.xmlToMap(xml);
            return resultMap;
        }catch (Exception e){
            throw  new GuiliException(20001,"查询错误");
        }
    }

    //添加支付记录和更新订单状态
    @Override
    public void updateOrderStatus(Map<String, String> map) {
        //从map钟获取订单号
        String orderNo = map.get("out_trade_no");
        QueryWrapper<TOrder> wrapper = new QueryWrapper();
        wrapper.eq("order_no",orderNo);
        TOrder tOrder = tOrderService.getOne(wrapper);
        //更新订单表订单状态
        if(tOrder.getStatus().intValue() == 1){return;}
        tOrder.setStatus(1);
        tOrderService.updateById(tOrder);
        //向支付表中添加支付记录
        TPayLog tPayLog = new TPayLog();

        tPayLog.setOrderNo(orderNo);  //订单号
        tPayLog.setPayTime(new Date()); //订单完成时间
        tPayLog.setPayType(1);//支付类型 1微信
        tPayLog.setTotalFee(tOrder.getTotalFee());//总金额(分)

        tPayLog.setTradeState(map.get("trade_state"));//支付状态
        tPayLog.setTransactionId(map.get("transaction_id")); //流水号
        tPayLog.setAttr(JSONObject.toJSONString(map));

        baseMapper.insert(tPayLog);
    }
}
